package com.rodrigo.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.rodrigo.model.Time;

public class TimeDAOImpl {
	
	EntityManagerFactory emf = Persistence.createEntityManagerFactory("PU");
	EntityManager em = emf.createEntityManager();

	@Autowired
	private SessionFactory sessionFactory;
	
	private Session getCurrentSession() {
		return sessionFactory.getCurrentSession();
	}

	public void addTime(Time time) {
		getCurrentSession().save(time);
	}

	public void updateTime(Time time) {
		Time timeToUpdate = getTime(time.getId());
		timeToUpdate.setName(time.getName());
		timeToUpdate.setRating(time.getRating());
		getCurrentSession().update(timeToUpdate);
		
	}

	

	public Time getTime(int id) {
		Time time = (Time) getCurrentSession().get(Time.class, id);
		return time;
	}

	public void deleteTime(int id) {
		Time time = getTime(id);
		if (time != null)
			getCurrentSession().delete(time);
	}

	@SuppressWarnings("unchecked")
	public List<Time> getTimes() {
		return getCurrentSession().createQuery("time origem").list();
	}

}

